package neural_network;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class CommandRunner {
	
	public static double runCommand(String cmdLine){
		double cost = 0.0;
		String line = "", lastLine = "";
		StringBuilder whole = new StringBuilder();
		boolean stdoutNeuro = true;
		try
		{

			Process p = Runtime.getRuntime().exec(cmdLine);
			BufferedReader input = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			while ((line = input.readLine()) != null)
			{
				if(stdoutNeuro)
					System.out.println(line);
				
				if (line != null)
				{
					if (line.trim().length() > 0)
					{
						lastLine = line;
						whole.append(line);
						if (line.contains("Cost: "))
						{
							String[] parts = line.split(": ");
							cost = Double.parseDouble(parts[1]);
						}
					}
				}
			}
			input.close();
		} catch (Exception err)
		{
			err.printStackTrace();
		}
//		System.out.println("{WHOLE STACK TRACE} \"" + whole.toString() + "\"");
//		System.out.println("{LAST LINE} \"" + lastLine + "\"");

		// return "[[ OUTPUT WRITTEN, ALL GOOD ]]".equals(lastLine);
		// return true;

		if (lastLine.contains("Accuracy: "))
		{
			System.out.println("Cost is " + cost);
			// double num = Double.parseDouble(lastLine.substring(23,
			// lastLine.length()));
			// return num;
			return cost;
		} else
		{
			System.out.println("Unexpected result from neuro? \"" + lastLine
					+ "\"");
			return -1;
		}

	}
	
	public static void main(String[] args) {
		CommandRunner.runCommand("octave metastaze.m no_pause no_graphic");
		CommandRunner.runCommand("octave metastaze_predictor.m no_pause no_graphic");

	}

}
